package jwt

import (
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"github.com/gin-gonic/gin"
	"time"
)

/*验证header中的token*/
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code error
		code = ecode.Ok
		token := c.GetHeader("token")
		if token == "" {
			code = ecode.ErrGetAuthToken
		} else {
			claims, err := app.ParseToken(token)
			if err != nil {
				code = ecode.ErrAuthTokenFail
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = ecode.ErrAuthExpire
			}
		}

		if code != ecode.Ok {
			app.Response(c, code)
			c.Abort()
			return
		}

		c.Next()
	}
}
